package com.main.quartz;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.CronScheduleBuilder.cronSchedule;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.main.bean.Task;
import com.main.util.SpringContextUtil;
import com.test.HelloJob;

public class QuartzUtil {

	private static String GROUP_DEFAULT="GROUP_DEFAULT";
	
	private Logger log=LoggerFactory.getLogger(this.getClass());
	private static QuartzUtil qt;
	//private static String path=null;
	//private static ApplicationContext ac=null;
	private static StdSchedulerFactory schedulerFactory =null;
	
	private QuartzUtil(){
	}
	
	public static QuartzUtil getQuartzUtil(){
		if(null==qt){
			qt=new QuartzUtil();
		}
		return qt;
	}
	static{
		 // path=QuartzUtil.class.getResource("/").toString().substring(6)+"spring/applicationContext.xml";
		 // ac=new ClassPathXmlApplicationContext("spring/applicationContext.xml");
		  schedulerFactory = new StdSchedulerFactory();
	}
	/**
	 * 判断是否属于任务类
	 * @param obj
	 * @return
	 */
	private boolean  isJob(Object obj){
		if(null==obj){
			log.info("通过注解获取实体类为空");
			return false;
		}else if(Job.class.isInstance(obj)){
			return true;
		}else{
			log.info("通过注解获取实体类,不是一个定时任务类");
			return false;
		}
	}
	/**
	 * 添加任务
	 */
	public boolean addJob(Task task) throws SchedulerException{
		if(null==task){
			return false;
		}
		
		log.info("通过注解名称："+task.getQuartz_ano_name()+"添加定时任务开始");
		Object obj=SpringContextUtil.getBean(task.getQuartz_ano_name());
		if(isJob(obj)){
			Scheduler scheduler = schedulerFactory.getScheduler();
			if(!scheduler.checkExists(new JobKey(task.getQuartz_ano_name(),QuartzUtil.GROUP_DEFAULT))){
				 
				JobDetail job = newJob(HelloJob.class)
						.withIdentity(task.getQuartz_ano_name(), QuartzUtil.GROUP_DEFAULT)
						.build();
				
				CronTrigger trigger = newTrigger()
			            .withIdentity(task.getQuartz_ano_name(), QuartzUtil.GROUP_DEFAULT)
			            .withSchedule(cronSchedule(task.getQuartz_corn()))
			            .build();
				scheduler.scheduleJob(job, trigger);
				if("2".equals(task.getQuartz_type())){//暂停
					TriggerKey tk=new TriggerKey(task.getQuartz_ano_name(),QuartzUtil.GROUP_DEFAULT);
					scheduler.pauseTrigger(tk);
					log.info("任务添加暂停成功");
				}
				if (!scheduler.isShutdown()) {  
					scheduler.start();  
	            }  
				return true;
			}else{
				log.info("注解名称："+task.getQuartz_ano_name()+"已存在任务中");
				TriggerKey tk=new TriggerKey(task.getQuartz_ano_name(),QuartzUtil.GROUP_DEFAULT);
				TriggerState ts=scheduler.getTriggerState(tk);
				if(TriggerState.PAUSED.equals(ts)){
					scheduler.resumeTrigger(tk);
					log.info("任务已恢复");
				}
			}
		}
		return false;
	}
	
	/**
	 * 移除任务
	 * @param task
	 * @return
	 * @throws SchedulerException
	 */
	public boolean removeJob(Task task) throws SchedulerException{
		if(null==task){
			return true;
		}
		log.info("注解名称:"+task.getQuartz_ano_name()+"任务将要别移除");
		Object obj=SpringContextUtil.getBean(task.getQuartz_ano_name());
		if(isJob(obj)){
			Scheduler scheduler = schedulerFactory.getScheduler();
			if(scheduler.checkExists(new JobKey(task.getQuartz_ano_name(),QuartzUtil.GROUP_DEFAULT))){
				scheduler.unscheduleJob(new TriggerKey(task.getQuartz_ano_name(), QuartzUtil.GROUP_DEFAULT));
				scheduler.deleteJob(new JobKey(task.getQuartz_ano_name(), QuartzUtil.GROUP_DEFAULT));
			}
			return true;
		}else{
			log.info("不是一个任务类");
			return false;
		}
		
	}
	
	/**
	 * 修改任务的表达式
	 * @param task
	 * @return
	 * @throws SchedulerException 
	 */
	public boolean modifyJob(Task task) throws SchedulerException{
		if(null==task){
			return false;
		}
		log.info("注解名称:"+task.getQuartz_ano_name()+"任务将要修改");
		Object obj=SpringContextUtil.getBean(task.getQuartz_ano_name());
		if(isJob(obj)){
			Scheduler scheduler = schedulerFactory.getScheduler();
			TriggerKey tk=new TriggerKey(task.getQuartz_ano_name(),QuartzUtil.GROUP_DEFAULT);
			if(scheduler.checkExists(tk)){
				CronTrigger trigger=(CronTrigger) scheduler.getTrigger(new TriggerKey(task.getQuartz_ano_name(), QuartzUtil.GROUP_DEFAULT));
				 if (trigger == null) {
					 log.info("未找到触发器");
		                return false;  
		            }  
				 String oldTime = trigger.getCronExpression();  
		            if (!oldTime.equalsIgnoreCase(task.getQuartz_corn())) {
		            	CronTrigger newTrigger = newTrigger()
					            .withIdentity(task.getQuartz_ano_name(), QuartzUtil.GROUP_DEFAULT)
					            .withSchedule(cronSchedule(task.getQuartz_corn()))
					            .build();
		                scheduler.rescheduleJob(tk, newTrigger);
		                log.info("更新成功");
		            }
			}
			return true;
		}else{
			log.info("不是一个任务类");
			return false;
		}
	}
	
	/**
	 * 暂停任务
	 * @param task
	 * @return
	 * @throws SchedulerException
	 */
	public boolean pauseJob(Task task) throws SchedulerException{
		if(null==task){
			return false;
		}
		log.info("注解名称:"+task.getQuartz_ano_name()+"任务将要暂停");
		Object obj=SpringContextUtil.getBean(task.getQuartz_ano_name());
		if(isJob(obj)){
			Scheduler scheduler = schedulerFactory.getScheduler();
			TriggerKey tk=new TriggerKey(task.getQuartz_ano_name(),QuartzUtil.GROUP_DEFAULT);
			if(scheduler.checkExists(tk)){
				scheduler.pauseTrigger(tk);
			}
			return true;
		}else{
			log.info("不是一个任务类");
			return false;
		}
	}
	
	/**
	 * 触发一次任务
	 * @param task
	 * @return
	 * @throws SchedulerException
	 */
	public boolean trigJob(Task task) throws SchedulerException{
		if(null==task){
			return false;
		}
		log.info("注解名称:"+task.getQuartz_ano_name()+"任务将要触发");
		Object obj=SpringContextUtil.getBean(task.getQuartz_ano_name());
		if(isJob(obj)){
			Scheduler scheduler = schedulerFactory.getScheduler();
			JobKey jk=new JobKey(task.getQuartz_ano_name(),QuartzUtil.GROUP_DEFAULT);
			if(scheduler.checkExists(jk)){
				scheduler.triggerJob(jk);
			}
			return true;
		}else{
			log.info("不是一个任务类");
			return false;
		}
	}
	public static void main(String[] args) throws SchedulerException, InterruptedException {
		Task t=new Task();
		t.setQuartz_ano_name("helloJob");
		t.setQuartz_corn("0/5 * * * * ?");
		QuartzUtil qu=new QuartzUtil();
		qu.addJob(t);
		Thread.sleep(10000L);
		qu.removeJob(t);
		qu.addJob(t);
		qu.pauseJob(t);
		Thread.sleep(10000L);
		qu.trigJob(t);
		qu.addJob(t);
	}
}
